<template>
  <div class="page-box">
    <!-- 筛选区域 -->
    <div v-show="flag" class="search-box">
      <!-- :inline="true" 表单在一行显示 -->
      <el-form size="mini" :inline="true" class="demo-form-inline">
        <el-form-item label="分类名称">
          <el-input v-model="params.catename" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="searchCate">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetCate">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 工具条区域 -->
    <div class="tabbar-box">
      <el-row type="flex" justify="space-between">
        <div>
          <el-button plain type="primary" icon="el-icon-plus" size="mini" @click="open('add')">新增</el-button>
          <el-button plain type="warning" icon="el-icon-download" size="mini" @click="exportExcel">导出</el-button>
        </div>

        <!-- 添加弹出层 -->
        <el-dialog
          :title="titleName"
          :visible.sync="dialogVisible"
          width="45%"
          :before-close="handleClose"
        >

          <el-form ref="ruleForm" :model="form" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="分类名称" prop="catename">
              <el-input v-model="form.catename" autocomplete="off" placeholder="请输入分类名" size="small" style="width:80%" />
            </el-form-item>
            <el-form-item label="图标class" prop="icon">
              <el-input v-model="form.icon" autocomplete="off" placeholder="请输入class名" size="small" style="width:40%;margin-right:10px" />
              <a class="link" target="_black" href="https://fontawesome.com.cn/v4/icons-ui/">具体参见fontawesome图标库</a>
            </el-form-item>
            <el-form-item label="排序大小">
              <el-input-number v-model="form.sort_num" :min="1" size="small" @change="handleChange" />
            </el-form-item>
            <el-form-item class="formButton">
              <el-button size="small" @click="callback">取消</el-button>
              <el-button type="primary" size="small" @click="confirm">确定</el-button>
            </el-form-item>

            <!-- </el-form-itemclass="dialog-footer"></el-form> -->

          </el-form>
        </el-dialog>

        <div>
          <el-button v-if="flag" icon="el-icon-arrow-up" circle size="mini" @click="flag=!flag" />
          <el-button v-else icon="el-icon-arrow-down" circle size="mini" @click="flag=!flag" />
          <el-button icon="el-icon-refresh" circle size="mini" @click="initDate()" />
          <el-button icon="el-icon-menu" circle size="mini" />
        </div>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table
        id="out-table"
        :data="list"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="id" label="分类ID" />
        <el-table-column prop="catename" label="分类名称" />
        <el-table-column prop="icon" label="图标class">
          <template #default="{row}">
            {{ row.icon }} <i class="fa " :class="row.icon" />
          </template>

        </el-table-column>
        <el-table-column prop="sort_num" label="权重" />
        <el-table-column prop="" label="操作">
          <template #default="{row}">
            <el-button type="primary" icon="el-icon-edit" circle @click="open('edit',row.id)" />
            <el-button type="danger" icon="el-icon-delete" circle @click="del(row.id)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[1,2,5, 10, 20, 30]"
        :page-size="params.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>
<script>
import { getCateList, addIcon, editCate, updateCate, delCate } from '@/api/content/cate'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      id: '',
      titleType: 'add',

      form: {
        catename: '',
        icon: '',
        sort_num: 10
      },
      rules: {
        catename: [
          { required: true, message: '分类名不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: 'class名不能为空', trigger: 'blur' }

        ]
      },
      dialogVisible: false,
      flag: true,
      list: [],
      params: {
        catename: '',
        page: 1,
        limit: 10
      },
      total: 0
    }
  },
  computed: {
    //! 判断弹出框的标题 title 是添加还是修改
    titleName() {
      let title = ''
      if (this.titleType === 'add') title = '添加分类'
      if (this.titleType === 'edit') title = '修改分类'
      return title
    }
  },

  created() {
    this.initDate()
  },
  methods: {
    //! 删除
    del(id) {
      console.log(id)
      this.$confirm('确定删除吗,是否继续?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delCate({ id })
        // console.log(this.list.length)
        if (this.list.length <= 1) {
          this.params.page -= 1
        }
        this.initDate()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    //! 修改功能
    async open(type, id) {
      this.titleType = type
      this.dialogVisible = true
      this.id = id
      if (type === 'edit') {
        const res = await editCate({ id })
        console.log(res)
        this.form = res.data
        this.default_data = res.default_data
        console.log(this.form)
      }
      // console.log(this.titleType)
    // const res = await editCate({ id })
    // console.log(res)
    // this.form = res.data
    },
    //! 计数器的函数
    handleChange(value) {
    // console.log(value)//! value 代表当前数值
      this.sort_num = value
    },
    //! 弹出层的函数
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    },
    //! 取消功能
    callback() {
      this.handleClose()
    },
    //! 添加功能
    // add(type) {
    //   this.titleType = type
    //   this.dialogVisible = true
    //   // this.$refs.ruleForm.validate(async isOk => {
    //   //   if (!isOk) return
    //   //   try {
    //   //     const res = await addIcon({
    //   //       catename: this.form.name,
    //   //       icon: this.form.icon,
    //   //       sort_num: this.num
    //   //     })
    //   //     this.handleClose()
    //   //     this.initDate()
    //   //     console.log(res)
    //   //   } catch (error) {
    //   //     console.log(error)
    //   //   }
    //   // })
    // },
    //! 分页器
    handleSizeChange(val) {
      this.params.limit = val
      this.params.page = 1
      this.initDate()
    },
    //! 分页器
    handleCurrentChange(val) {
      this.params.page = val
      // console.log(this.list.length)

      this.initDate()
    },
    //! 搜索功能
    searchCate() {
      this.params.page = 1
      this.initDate()
    },
    //! 重置
    resetCate() {
      this.params = {
        catename: '',
        page: 1,
        limit: 10
      }
      this.initDate()
    },
    async initDate() {
      const res = await getCateList(this.params)
      // console.log(res)
      this.list = res.data.data
      this.total = res.data.count
    },
    async confirm() {
      if (this.titleType === 'add') {
        this.$refs.ruleForm.validate(async isOk => {
          if (!isOk) return
          try {
            await addIcon(this.form)
            this.handleClose()
            this.initDate()
          // console.log(res)
          } catch (error) {
            console.log(error)
          }
        })
      }
      if (this.titleType === 'edit') {
        await updateCate({
          catename: this.form.catename,
          default_data: 1,
          icon: this.form.icon,
          id: this.id,
          sort_num: this.form.sort_num

        })
        // console.log(res)
        // this.form = res.data
        this.handleClose()
        this.initDate()
      // console.log(res)
      }
    },
    exportExcel() {
      var xlsxParam = { raw: true }
      var wb = XLSX.utils.table_to_book(
        document.querySelector('#out-table'),
        xlsxParam
      )
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          '用户个人信息.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }
  }
}
</script>
<style lang="scss" scoped>
  .page-box {
    padding: 20px;
    .search-box,.tabbar-box {
      padding-top: 10px;
      border:  1px solid #eee;
      margin-bottom: 20px;
      height: 50px;
    }

    .link:hover {
        color: green;
        border-bottom: 1px solid green;
    }

    .formButton{
        display: flex;
        justify-content: flex-end;
    }
  }

</style>
